package com.bwie.pay;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 军哥
 * @version 1.0
 * @description: 阿里支付
 * @date 2024/10/23 17:52
 */

public class AlipayUtils {
    /**
     * 获取订单编号
     * @return
     */
    public static String getOrderNo() {
        String url = "https://www.shenmazong.com/alipay/getOrderNo";

        HttpRequest request = HttpRequest.get(url);
        String body = request.execute().body();

        // 获取请求状态
        JSONObject jsonObject = JSON.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if(code != 0) {
            return null;
        }

        // 获取订单号
        String orderNo = jsonObject.getString("data");
        return orderNo;
    }

    /**
     * 生成支付码
     * @param orderNo
     * @param description
     * @param amount
     * @return 支付码
     */
    public static String postOrderObj(String orderNo, String description, Integer amount) {
        String url = "https://www.shenmazong.com/alipay/postOrderObj";

        // 准备请求参数
        JSONObject paramObj = new JSONObject();
        paramObj.put("outTradeNo", orderNo);
        paramObj.put("description", description);
        paramObj.put("amount", amount);
        paramObj.put("attach", "");


        // 发送 POST 请求
        HttpResponse response = HttpRequest.post(url)
                .contentType("application/json") // 设置 Content-Type 为 application/json
                .body(paramObj.toJSONString()) // 设置请求体为 JSON
                .execute(); // 执行请求
        String body = response.body();

        // 获取请求状态
        JSONObject jsonObject = JSON.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if(code != 0) {
            return null;
        }

        // 获取支付码
        String payUrl = jsonObject.getString("data");
        return payUrl;
    }

    /**
     * 检查订单支付状态
     * @param orderNo
     * @return true:已支付，false:未支付
     */
    public static boolean checkPayStatus(String orderNo) {
        String url = "https://www.shenmazong.com/alipay/getOrderInfo?orderNo=" + orderNo;

        // 发送请求
        HttpRequest request = HttpRequest.get(url);
        String body = request.execute().body();

        // 获取请求状态
        JSONObject jsonObject = JSON.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if(code != 0) {
            return false;
        }

        // 获取订单信息
        JSONObject data = jsonObject.getJSONObject("data");
        Integer status = data.getInteger("orderStatus");
        if(status == 1) {
            return true;
        }
        return false;
    }
}
